import 'package:local_auth/local_auth.dart';

class BiometricService {
  final LocalAuthentication _auth = LocalAuthentication();

  /// 检查设备是否支持生物识别
  Future<bool> isAvailable() async {
    try {
      final canCheck = await _auth.canCheckBiometrics;
      final isSupported = await _auth.isDeviceSupported();
      final types = await _auth.getAvailableBiometrics();
      return canCheck && isSupported && types.isNotEmpty;
    } catch (e) {
      return false;
    }
  }

  /// 获取可用的生物识别类型
  Future<List<BiometricType>> getAvailableTypes() async {
    try {
      return await _auth.getAvailableBiometrics();
    } catch (e) {
      return [];
    }
  }

  /// 执行生物识别验证
  Future<bool> authenticate({String reason = '请验证身份'}) async {
    try {
      return await _auth.authenticate(
        localizedReason: reason,
        options: const AuthenticationOptions(
          biometricOnly: true, // 只允许生物识别
          stickyAuth: true,    // App切后台回来继续验证
          useErrorDialogs: true, // 系统错误提示
        ),
      );
    } catch (e) {
      return false;
    }
  }

  /// 取消验证（可选）
  Future<void> stopAuthentication() async {
    try {
      await _auth.stopAuthentication();
    } catch (_) {}
  }
}
